package cn.maxhou.controller;

import cn.maxhou.entity.SysUser;
import cn.maxhou.service.SysUserService;
import cn.maxhou.util.Constants;
import com.alibaba.fastjson2.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;

@Controller
@RequestMapping("/main")
public class PasswdController extends BaseController{
    private static final Logger LOGGER= LoggerFactory.getLogger(PasswdController.class);
    @Autowired
    private SysUserService sysUserService;

    @RequestMapping("/changePwd")
    public String tochangePwd(){
        return "sys/changePwd";
    }

    @ResponseBody
    @RequestMapping("/oldPasswordCheck")
    public String oldPasswordCheck(@RequestParam String oldPassword){
        HashMap<String,Object> resultMap=new HashMap<String,Object>();
        //通过父类的session方法获取登录用户,由于泛型自动转换无需强转
        SysUser loginUser=session(Constants.SESSION_USER);
        try {
            SysUser Account = sysUserService.findByAccount(loginUser.getAccount());
            if (oldPassword.equals(Account.getPassword())){
                resultMap.put("pass", 1);
            }else {
                resultMap.put("pass", 0);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return JSON.toJSONString(resultMap);
    }
    @PostMapping("/changePwd")
    public String dochangePwd(String oldPassword, String password, String confirmpassword, Model model){
        //通过父类的session方法获取登录用户,由于泛型自动转换无需强转
        SysUser loginUser=session(Constants.SESSION_USER);
        try {
            SysUser Account = sysUserService.findByAccount(loginUser.getAccount());
            if (!oldPassword.equals(Account.getPassword())){
                model.addAttribute("error", "旧密码不正确");
            }else if (!password.equals(confirmpassword)){
                model.addAttribute("error", "两次密输入不一致");
            }else {
                Account.setPassword(password);
                sysUserService.changePassword(Account);
                model.addAttribute("error", "密码修改成功");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return "sys/changePwd";
    }
}
